package com.shenzw.mybatisdemo.service.impl;

import com.shenzw.mybatisdemo.domain.User;
import com.shenzw.mybatisdemo.repository.UserRepository;
import com.shenzw.mybatisdemo.service.UserService;
import com.shenzw.mybatisdemo.utils.MybatisBatchUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shenzw
 * @date 2023/8/30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    private final MybatisBatchUtils mybatisBatchUtils;

    @Override
    public User getUser(int id) {
        return userRepository.select(id);
    }

    /**
     * 演示 Mybatis 批处理 Executor.BATCH
     */
    @Override
    public void batchInsertUser() {
        List<User> userList = new ArrayList<>(2000);
        for (int i = 0; i < 100000; i++) {
            User user = new User();
            user.setUserName("测试 " + i);
            user.setPassword(i);
            user.setSex(i % 2 == 0 ? "男" : "女");
            userList.add(user);
        }


        // 普通 foreach 批量插入
//        userRepository.insertBatch(userList); // 2w数据：0.6s  20w数据：5339

        mybatisBatchUtils.batchUpdateOrInsert(userList, UserRepository.class, (user, userRepository2) -> userRepository2.insert(user)); // ？？？ 16，17秒？？？？我笑了 2w数据：16，17秒  20w数据：178159

    }

    /**
     * 新增用户
     *
     * @param user 用户信息
     * @return User
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer insertUser(User user) {
        Integer insert = userRepository.insert(user);
        try {
            int i = 1 / 0;
        } catch (Exception e) {
            log.error("错误", e);
            e.printStackTrace();
//            throw e;
        }
        return insert;
    }
}
